package com.majx.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class TokenUtil {
    //有效时长
    private static final long EXPIRE_TIME = 24 * 60 * 60 * 10000;

    //密钥
    private static final String TOKEN_SECRET = "majx";

    /**
     * 签名生成
     * @param username
     * @return
     */
    public static String sign(String username) {
        String token = null;

        try {
            Date expireAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            token = JWT.create() //创建jwt实例对象
                    .withIssuer("auth0") //签发者
                    .withClaim("username", username) //载荷
                    .withExpiresAt(expireAt) //过期时间
                    .sign(Algorithm.HMAC256(TOKEN_SECRET)); //加密算法
        } catch (Exception e) {
            e.printStackTrace();
        }

        return token;

    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public static boolean verify(String token) {
        try {
            System.out.println("校验开始");
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET))
                    .withIssuer("auth0").build();

            DecodedJWT jwt = verifier.verify(token);

            System.out.println("认证通过");
            System.out.println("username="+jwt.getClaim("username").asString());

            SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd yyyy hh:mm:ss z", Locale.ENGLISH);
            System.out.println("过期时间（标准）"+new SimpleDateFormat("yyyy-MM-dd").format(jwt.getExpiresAt()));

            System.out.println("过期时间"+jwt.getExpiresAt());

            return true;
        } catch (Exception e) {
            System.out.println("认证失败"+e);

            return false;
        }


    }



}
